﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Net.Sockets;
using Windows.Networking.Connectivity;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using WPHttpServer;
using System.Text.RegularExpressions;
using System.Windows.Resources;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace Beyoung.HelloReading.WP
{
    public partial class WifiTransfer : PhoneApplicationPage
    {
        public WifiTransfer()
        {
            InitializeComponent();
            this.Loaded += WifiTransfer_Loaded;
        }

        void WifiTransfer_Loaded(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            IPAddress ipa = Find();
            tbIP.Text ="http://"+ ipa.ToString();
            // create the http server            
            HttpServer httpServer = new HttpServer(ipa.ToString());

            //register an request handler which will handle the posted form data
            httpServer.RegisterRequestHandler(new Regex(@"/|.+\.js|.+\.css|.+\.swf"), request =>
            {
                // get the data send as form data
                //HtmlResponseContentProvider formDataProvider = request.Content as HtmlResponseContentProvider;
                string requestFileName = request.Uri.LocalPath;
                if (requestFileName == string.Empty || requestFileName=="/")
                {
                    requestFileName = "/wifi.htm";
                }
                if (requestFileName == "/upload.htm")
                {
                    RequestFormData rf = request.Content as RequestFormData;
                    HttpResponse rsp3 = new HttpResponse(WPHttpServer.HttpStatusCode.Ok);
                    return rsp3;
                }
                if (requestFileName.Contains(".ico"))
                {
                    requestFileName = "";
                    HttpResponse rsp2 = new HttpResponse(WPHttpServer.HttpStatusCode.NotFound);
                    return rsp2;
                }
                
                HttpResponse rsp = new HttpResponse(WPHttpServer.HttpStatusCode.Ok);
                Uri uri = new Uri("/Beyoung.HelloReading.WP;component/Resources/wifipage2"+requestFileName, UriKind.Relative);
                StreamResourceInfo sm = Application.GetResourceStream(uri);
                StreamReader sr=new StreamReader (sm.Stream);
                if (requestFileName.Contains(".htm"))
                {
                    rsp.Content = new HtmlResponseContentProvider(sr.ReadToEnd());
                }
                if (requestFileName.Contains(".swf"))
                {
                    byte[] buffer = new byte[sm.Stream.Length];
                    sm.Stream.Read(buffer, 0, buffer.Length);
                    rsp.Content = new FlashResponseContentProvider(buffer);
                }
                if (requestFileName.Contains(".png"))
                {
                    byte[] buffer=new byte[sm.Stream.Length];
                    sm.Stream.Read(buffer,0,buffer.Length);
                    rsp.Content = new ImageResponseContentProvider(buffer, ImageFormat.Png);
                }
                if (requestFileName.Contains(".js"))
                {
                    rsp.Content = new JsResponseContentProvider(sr.ReadToEnd());
                }
                if (requestFileName.Contains(".css"))
                {
                    rsp.Content = new CssResponseContentProvider(sr.ReadToEnd());
                }
                
                
                return rsp;
                //return new HttpResponse(WPHttpServer.HttpStatusode.Ok);
            });

            httpServer.Start();
            //StartListen();
        }
        /// <summary>
        /// 开始监听
        /// </summary>
        private async void StartListen()
        {
            StreamSocketListener listener = new StreamSocketListener();
            listener.ConnectionReceived += listener_ConnectionReceived; 
            await listener.BindServiceNameAsync("80");
        }

        private async void listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            byte[] requestBuffer;
            using( DataReader reader = new DataReader(args.Socket.InputStream))
            {
                reader.InputStreamOptions = InputStreamOptions.Partial;
                await reader.LoadAsync(1024);
                requestBuffer = new byte[reader.UnconsumedBufferLength];
                reader.ReadBytes(requestBuffer);
                string request = System.Text.UTF8Encoding.UTF8.GetString(requestBuffer, 0, requestBuffer.Length);
                //while (reader.UnconsumedBufferLength>0)
                //{
                //    tboutput.Text = reader.ReadString(reader.UnconsumedBufferLength);
                //}
            }
            using(DataWriter dataWriter=new DataWriter(args.Socket.OutputStream))
            {
                    dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;
                    string header = String.Format("HTTP/1.1 200 OK\r\n" +
                              "Content-Length: {0}\r\n" +
                              "Connection: close\r\n\r\n",
                              200);

                    dataWriter.WriteString(header);
                    dataWriter.WriteString("hi girl");
                    await dataWriter.StoreAsync();

                    // For the in-memory stream implementation we are using, the flushAsync call is superfluous,
                    // but other types of streams may require it.
                    await dataWriter.FlushAsync();

                    // In order to prolong the lifetime of the stream, detach it from the DataWriter so that it 
                    // will not be closed when Dispose() is called on dataWriter. Were we to fail to detach the 
                    // stream, the call to dataWriter.Dispose() would close the underlying stream, preventing 
                    // its subsequent use by the DataReader below.
                    dataWriter.DetachStream();
            }
        }
        /// <summary>
        /// 获取本机IP地址
        /// </summary>
        /// <returns></returns>
        public static IPAddress Find()
        {
            List<string> ipAddresses = new List<string>();

            var hostnames = NetworkInformation.GetHostNames();
            foreach (var hn in hostnames)
            {
                if (hn.IPInformation != null)
                {
                    string ipAddress = hn.DisplayName;
                    ipAddresses.Add(ipAddress);
                    Debug.WriteLine(ipAddress);
                }
            }

            IPAddress address = IPAddress.Parse(ipAddresses[0]);
            return address;
        }
    }
}